(function() {
    'use strict';

    /**
     * @ngdoc directive
     * @name webApp.directive:ueditor
     * @description
     * # ueditor 
     */
    angular.module('webApp')
        .run(["$templateCache", "dataService",
            function($templateCache, dataService) {
                var tplName = "views/directives.imgcc.html";
                dataService.tpl(tplName).then(function(html) {
                    $templateCache.put(tplName, html);
                });
            }
        ]).run(["$templateCache", "dataService",
            function($templateCache, dataService) {
                var tplName = "views/directives.videoset.html";
                dataService.tpl(tplName).then(function(html) {
                    $templateCache.put(tplName, html);
                });
            }
        ])
        .directive('ueditor', function() {
            var ueditor;
            return {
                restrict: 'E',
                require: 'ngModel',
                template: '<span><div id="{{uid}}" class="ueditor" style="width:{{width}}px;" ng-model="myUeditor" config="config" ></div><attachment id="{{uid}}uploadattach" setback="attachBack(attach)" owner-id="item.item_id ?item.item_id:1" owner-type="item" dhf-ng-model="attchUrl" xtype="url" mult="false" title="添加图片" use-type="png,jpeg,gif,jpg" style="display:none;" checkbox="1"></attachment><attachment id="{{uid}}uploadVideo" setback="attachVideoBack(attach)" owner-id="item.item_id ?item.item_id:1" owner-type="item" dhf-ng-model="attchUrl" xtype="url" mult="false" title="添加视频" use-type="mp4,avi" style="display:none;" max-size="30MB"></attachment><a-url id="{{uid}}aurl" setback="setpath(path,ctype,cid,cover)" style="display:none;" ></a-url></span>',
                scope: {
                    item: "=", //商品数据
                    ngModel: "=",
                    uid: "@",
                    width: "@",
                    // width: "@",
                },

                controller: ['$scope', 'dataService', '$timeout', '$compile', '$templateCache', function($scope, dataService, $timeout, $compile, $templateCache) {
                    var lang = window.localStorage.lang || 'cn';
                    lang = lang == 'cn' ? 'zh-cn' : lang;
                    $scope.width = $scope.width || 750;
                    $scope.config = {
                        lang: lang,
                        initialFrameWidth: "500px",
                        autoFloatEnabled: false,
                        toolbars: [
                            [
                                'source', '|', 'undo', 'redo', '|',
                                'bold', 'italic', 'underline', 'strikethrough', 'removeformat', '|', 'forecolor', 'backcolor', 'selectall', 'cleardoc', '|',
                                'lineheight', '|',
                                'fontfamily', 'fontsize', '|',
                                'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|',
                                'horizontal', 'searchreplace', '|',
                                'insertparagraphbeforetable', //"表格前插入行"
                                'inserttable', //插入表格
                                'edittable', //表格属性
                                'deletetable', //删除表格
                                'insertrow', //前插入行
                                'insertcol', //前插入列
                                'deleterow', //删除行
                                'deletecol', //删除列
                                'edittd', '|', //单元格属性
                            ]
                        ],
                        allowDivTransToP: false
                    };

                    $scope.attachVideoBack = function(attach) {
                        showVideoPop(attach);
                    }

                    function showVideoPop(attach) {
                        $scope.autoPlay = false;

                        $.alert({
                            backdrop: 'static',
                            keyboard: true,
                            title: '{{"视频设置" | translate}}',
                            // body: '<span> <div class="control-group"><div class="controls"><label></label></div></span>',
                            body: $templateCache.get("views/directives.videoset.html"),
                            okBtn: '{{"ok" | translate}}',
                            closeBtn: true,
                            transition: true,
                            width: 'small',
                            height: 200,
                            show: function(e) {
                                $compile($(e.currentTarget).contents())($scope);
                                return true;
                            },
                            okHide: function(e) {
                                $scope.setVideo(attach);
                            },
                        });
                    }
                    $scope.setVideo = function(attach) {
                        execCommand('<a cpath="' + attach + '" atype="video" ctype="video" >　 <video width="400" height="300" src="' + attach + '" autoplay="' + $scope.autoPlay + '" controls="controls"></video></a>');
                    }
                    $scope.attachBack = function(attach) {
                        // console.error("attachBack",attach);
                        showPop(attach);
                    }

                    function showPop(attach) {
                        $scope.cicui = 1;
                        $scope.isPreview = 0
                        $scope.lcc = {
                            "imgw": 100,
                            "imgh": 100
                        };
                        $.alert({
                            backdrop: 'static',
                            keyboard: true,
                            title: '{{"设置图片" | translate}}',
                            // body: '<span> <div class="control-group"><div class="controls"><label></label></div></span>',
                            body: $templateCache.get("views/directives.imgcc.html"),
                            okBtn: '{{"ok" | translate}}',
                            closeBtn: true,
                            transition: true,
                            width: 'small',
                            height: 200,
                            show: function(e) {
                                $compile($(e.currentTarget).contents())($scope);
                                return true;
                            },
                            okHide: function(e) {
                                $scope.savepath(attach);
                            },
                        });
                    }

                    $scope.savepath = function(attachs) {
                        var path = '';
                        _.map(attachs, function(one, key) {
                            var attach = one.path;
                            if ($scope.cicui == 0) {
                                path += '<img src="' + attach + '" ispreview="' + $scope.isPreview + '" />';
                            }

                            if ($scope.cicui == 1) {
                                path += '<img src="' + attach + '" ispreview="' + $scope.isPreview + '" style="width:100%"/>';
                            }

                            if ($scope.cicui == 2) {
                                path += '<img src="' + attach + '" ispreview="' + $scope.isPreview + '" style="width:' + $scope.lcc.imgw + 'px;height:' + $scope.lcc.imgh + 'px"/>';
                            }
                        });
                        console.error("path", path);
                        execCommand(path);
                    }

                    function execCommand(html) {
                        try {
                            $timeout(function() {
                                //ueditor.execCommand('drafts');
                                ueditor.focus();
                                console.error("html", html);
                                ueditor.execCommand('inserthtml', html, !0);
                                // console.error("ueditor.getContent()", ueditor.getContent());
                                $scope.ngModel = ueditor.getContent();
                            });
                        } catch (e) {
                            console.error("e", e);
                        }
                    }

                    //返回连接ur
                    $scope.setpath = function(path, ctype, cid, cover) {
                        console.error("ctype", ctype);
                        if (ueditor.selection.getStartElementPath()[0].tagName == "A") {
                            var obj = {
                                'href': path,
                                'target': "_blank",
                                'ctype': ctype,
                                'cpath': path,
                                'cid': cid,
                            }
                            if (ctype == 'map') {
                                // execCommand('<a ctype="map" lat="' + cid.lat + '" lng="' + cid.lng + '"><img src="https://img.alicdn.com/imgextra/i2/20841398/TB2XjX0XoEIL1JjSZFFXXc5kVXa-20841398.jpg" ctype="map"/></a>')
                            } else {
                                ueditor.execCommand('link', UE.utils.clearEmptyAttrs(obj));
                            }
                            $scope.ngModel = ueditor.getContent();
                        } else {
                            if (ctype == "video") {
                                execCommand('<a cpath="' + path + '" atype="video" ctype="video" cover="' + cover + '"> 　<video width="100%" height="300" src="' + path + '" controls="controls"></video></a>');
                                // ueditor.setContent('<a cpath="' + path + '" atype="video" ctype="video" cover="' + cover + '"> 　<video width="100%" height="300" src="' + path + '" controls="controls"></video></a>', true);
                            } else if (ctype == "map") {
                                execCommand('<a ctype="map" lat="' + cid.lat + '" lng="' + cid.lng + '" address="' + cover + '"><img src="https://img.alicdn.com/imgextra/i2/20841398/TB2XjX0XoEIL1JjSZFFXXc5kVXa-20841398.jpg" ctype="map"/></a>')
                            } else {
                                //高亮后，才能获取到选中文本，当选中字失去焦点的情况下是获取不到的选中文本的
                                ueditor.selection.getRange().applyInlineStyle("a", {
                                    "href": path,
                                    "target": "_blank",
                                    "cpath": path,
                                    "ctype": ctype,
                                    "cid": cid
                                });
                            }
                            $scope.ngModel = ueditor.getContent();
                        }
                    }

                    //添加一个按钮
                    UE.registerUI('attachment aurl video map', function(editor, uiName) {
                            //注册按钮执行时的command命令，使用命令默认就会带有回退操作
                            editor.registerCommand(uiName, {
                                execCommand: function() {
                                    ueditor = editor;
                                    if (uiName == "attachment") {
                                        angular.element('#' + $scope.uid + 'uploadattach a').triggerHandler('click');
                                    } else if (uiName == "aurl") {
                                        angular.element('#' + $scope.uid + 'aurl a').triggerHandler('click')
                                    } else if (uiName == "map") {
                                        // ueditor.setContent('<a ctype="map"><img src="https://img.alicdn.com/imgextra/i2/20841398/TB2XjX0XoEIL1JjSZFFXXc5kVXa-20841398.jpg" ctype="map"/></a>', true);
                                        // execCommand('<a ctype="map"><img src="https://img.alicdn.com/imgextra/i2/20841398/TB2XjX0XoEIL1JjSZFFXXc5kVXa-20841398.jpg" ctype="map"/></a>');
                                    } else if (uiName == "video") {
                                        angular.element('#' + $scope.uid + 'uploadVideo a').triggerHandler('click')
                                    }
                                }
                            });
                            var btn1 = {
                                name: "",
                                cssRules: ""
                            }
                            if (uiName == "attachment") {
                                btn1.name = "添加图片",
                                    btn1.cssRules = "background-position: -380px 0px;"
                            } else if (uiName == "aurl") {
                                btn1.name = "添加连接",
                                    btn1.cssRules = "background-position: -500px 0px;"
                            } else if (uiName == "map") {
                                // btn1.name = "添加地图",
                                //     btn1.cssRules = "background-position: -40px -40px;"
                            } else if (uiName == "video") {
                                btn1.name = "添加视频",
                                    btn1.cssRules = "background-position: -320px -20px;"
                            }
                            //创建一个button
                            var btn = new UE.ui.Button({
                                //按钮的名字
                                name: btn1.name,
                                //提示
                                title: btn1.name,
                                //需要添加的额外样式，指定icon图标，这里默认使用一个重复的icon
                                cssRules: btn1.cssRules,
                                //点击时执行的命令
                                onclick: function() {
                                    //这里可以不用执行命令,做你自己的操作也可
                                    editor.execCommand(uiName);
                                }
                            });
                            editor.addListener('contentChange', function(type) {
//                                 console.error(" editor.getContent()", editor.key, type);
                                $scope.ngModel = editor.getContent();
                            });

                            //当点到编辑内容上时，按钮要做的状态反射
                            // editor.addListener('selectionchange', function() {
                            //     var state = editor.queryCommandState(uiName);
                            //     if (state == -1) {
                            //         btn.setDisabled(true);
                            //         btn.setChecked(false);
                            //     } else {
                            //         btn.setDisabled(false);
                            //         btn.setChecked(state);
                            //     }
                            // });
                            // editor.addListener('afterSelectionChange', function(editor) {
                            //     // console.log('选区发生改变',editor);
                            //     // console.error(ueditor.selection.getStartElementPath(),ueditor.selection.getRange(),ueditor.selection.getText());
                            //     Range = ueditor.selection.getRange();
                            //     selection = ueditor.selection;
                            //     // console.error("cccccccc",Range,selection.getStartElementPath());
                            //     if (selection.getStartElementPath()[0].tagName == "A") {
                            //         // editor.ui
                            //     }
                            //     // Range.select();
                            // })
                            //因为你是添加button,所以需要返回这个button
                            return btn;
                        }
                        /*index 指定添加到工具栏上的那个位置，默认时追加到最后,editorId 指定这个UI是那个编辑器实例上的，默认是页面上所有的编辑器都会添加这个按钮*/
                    );
                    $('body').off('openAurl').on('openAurl', function(e, data) {
                        $('#aurl a').click();
                    });
                    $scope.$on("$destroy", function() {
                        // console.error("xiaohui");
                        // ueditor.destroy();
                    })
                }],
                link: function(scope, element, attrs, ctrl) {

                    // scope.style = attrs.style ? attrs.style : "width:100%";
                    // console.error("attrs", attrs);
                    scope.$watch('myUeditor', function(newValue, oldValue, scope) {
                        ctrl.$setViewValue(newValue);
                    });

                    ctrl.$render = function() {
                        scope.myUeditor = (ctrl.$isEmpty(ctrl.$viewValue) ? "" : ctrl.$viewValue);
                    };

                }
            }
        });
})();